package dao

import (
	"gitee.com/wzpwzy/gogii/conf"
	"gitee.com/wzpwzy/gogii/tools"
	"strings"
)

// Case2Camel 下划线转驼峰(大驼峰)
func Case2Camel(name string) string {
	name = strings.Replace(name, "_", " ", -1) // 根据_来替换成
	name = strings.Title(name)                 // 全部大写
	return strings.Replace(name, " ", "", -1)  // 删除空格
}

func CreateDao(op conf.Options) {

	content := `package `
	if op.Namespace == "" {
		content += `dao`
	} else {
		content += op.Namespace
	}

	if op.ModelsNamespace == "" {
		op.ModelsNamespace = "models"
	}
	filename := op.Name
	if conf.MasterDbConfig.Prefix != "" {
		op.Name = strings.Replace(op.Name, conf.MasterDbConfig.Prefix, "", -1)
	}
	op.Name = Case2Camel(op.Name)
	content += `

import (
	"gorm.io/gorm"
	"` + op.ModelsNamespace + `"
)

type ` + op.Name + `Dao struct {
	db  *gorm.DB
}

func New` + op.Name + `(db *gorm.DB) *` + op.Name + `Dao {
	dao := &` + op.Name + `Dao{
		db:  db,
	}
	return dao
}

//添加
func (c *` + op.Name + `Dao) Create(v *model.` + op.Name + `)(id int, err error) {
	err = c.db.Create(&v).Error
	return v.ID,err
}

//修改
func (c *` + op.Name + `Dao) Update(v *model.` + op.Name + `)(id int, err error) {
	err = c.db.Model(&model.` + op.Name + `{}).Where("id = ?",v.ID).Updates(&v).Error
	return v.ID,err
}

//删除
func (c *` + op.Name + `Dao) Delete(v *model.` + op.Name + `)(id int, err error) {
	err = c.db.Delete(&v).Error
	return v.ID,err
}

func (c *` + op.Name + `Dao) GetInfo(where map[string]interface{}) (model.` + op.Name + `, error) {
	var v model.` + op.Name + `
	err :=c.db.Where(where).Find(&v).Error
	return v,err
}

func (c *` + op.Name + `Dao) GetTotal(where map[string]interface{}) (int64, error) {
	var num int64
	key, val, _ := db.WhereBuild(where)
	err := c.db.Model(&model.` + op.Name + `{}).Where(key, val...).Count(&num).Error
	return num, err
}

func (c *` + op.Name + `Dao) GetList(where map[string]interface{},order string,pageSize int,page int) ([]model.` + op.Name + `,error) {
	var v []model.` + op.Name + `
	offset := (page - 1) * pageSize
	err :=c.db.Where(where).Order(order).Limit(pageSize).Offset(offset).Find(&v).Error
	return v,err
}`

	if op.Path == "" {
		filename = conf.DaoPath + filename + ".go"
	} else {
		filename = op.Path + filename + ".go"
	}
	tools.Write(filename, op.Name, content, op.Path)
}
